<?php namespace app\service\controller;

require("../vendor/qiniu/autoload.php");
use think\Controller;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;


/**
 * 文件服务层
 */
class Qiniu extends Controller{
	
	private $qiniuConfig = '';		//七牛云配置项
	private $auth = '';				//初始化鉴权对象
	private $url = [
		'uploadImage' => 'http://upload.qiniup.com',
	];
	
	public function __construct(){
		parent::__construct();
		if(empty($this -> qiniuConfig)) $this -> qiniuConfig = config('QI_NIU');
		if(empty($this -> auth)) $this -> auth = new Auth($this -> qiniuConfig['accessKey'], $this -> qiniuConfig['secrectKey']);
	}
	
	/**
	 * 上传文件(file)
	 * @param	string	$filePath	要上传的文件路径
	 * @param	string	$suffix		要上传的文件后缀
	 * @return	array
	 */
	public function upLoadFile($filePath = '', $suffix = ''){
		
//		$mime = substr(strrchr($filePath, '.'), 1);
		$fileName = $this -> createFileName($suffix);		//生成文件名
		
		$res = $this -> upFile($fileName, $filePath, 2);	//上传
		
		$outArr['code'] = (isset($res['0']['key']) && !empty($res['0']['key'])) ? '1' : '50003';
		$outArr['info'] = $this -> qiniuConfig['domain'] . isset($res[0]['key']) ? $res[0]['key'] : '';
		return $outArr;
	}
	
	/**
	 * 上传文件(base64)没用上
	 * @param	string	$base64	要上传的文件(base64)
	 * @return	array
	 */
	public function upLoadFileBase64($base64){
		$base64 = trim($base64);
		
//		校验base64格式
		$base64Size = $this -> checkBase64($base64);
		if($base64Size['code'] != 'ok'){
			$outArr['code'] = $base64Size['code'];
			return $outArr;
		}
		
		$base64 = str_replace('data:' . $base64Size['info']['mime'] . ';base64,', '', $base64);			//去除base64头
		$base64 = base64_decode($base64);					//解码
		
		$mime = explode('/', $base64Size['info']['mime'])[1];
		$fileName = $this -> createFileName($mime);			//生成文件名
		
		$res = $this -> upFile($fileName, $base64, 1);		//上传
		
		$outArr['code'] = (isset($res['0']['key']) && !empty($res['0']['key'])) ? 'ok' : '50003';
		$outArr['info'] = $this -> qiniuConfig['domain'] . isset($res[0]['key']) ? $res[0]['key'] : '';
		return $outArr;
	}
	
	/**
	 * 校验base64格式
	 * @param	string	$base64		base64字符串
	 */
	private function checkBase64($base64){
		$base64Size = getimagesize($base64);
		$fileType = explode('/', $base64Size['mime']);
		$outArr['code'] = 'ok';
		$outArr['info'] = $base64Size;
		switch ($fileType[0]) {
			case 'image':
				if( !in_array($fileType[1], $this -> qiniuConfig['image']['type']) ) $outArr['code'] = '40011';
				break;
			default: $outArr['code'] = '40011'; break;
		}
		return $outArr;
	}
	
	/**
	 * 生成文件名
	 * @param	string	$mime	文件后缀
	 * @returm	string	年月日时分秒 + 13位时间戳 + 3位随机数 + 文件后缀
	 */
	private function createFileName($mime){
//		return date("YmdHis", time()) . getUnixTimestamp() . rand(100, 999) . '.' . explode('/', $base64Size['info']['mime'])[1];
		return date("YmdHis", time()) . getUnixTimestamp() . rand(100, 999) . '.' . $mime;
	}

	/**
	 * 上传
	 * @param	string	$fileName	生成的文件名
	 * @param	string	$file		要上传的文件
	 * @param	string	$upType		上传类型（1：base64，2：要上传文件的本地路径）
	 * @return	array
	 */
	public function upFile($fileName, $file, $upType){
		$upLoadMgr = new UploadManager();
		switch ($upType) {
			case 1:
				return $upLoadMgr -> put( $this -> getUploadToken(), $fileName, $file);
				break;
			case 2:
				return $upLoadMgr -> putFile( $this -> getUploadToken(), $fileName, $file);
				break;
			default: return FALSE; break;
		}
	}
	
	/**
	 * 获取文件上传凭证
	 * @return	string	上传凭证token
	 */
	private function getUploadToken(){
		return $this -> auth -> uploadToken($this -> qiniuConfig['bucket'], null, 3600);
//		$key = $this -> auth->getAccessKey();
	}
	
}
